package com.mf.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.Random;

public class RandomRule_MF extends AbstractLoadBalancerRule {

    private int total = 0;
    private int currentIndex = 0;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }


    public Server choose(ILoadBalancer lb,Object key) {
        if(lb==null){
            return null;
        }
        Server server = null;

        while (server == null){
            if(Thread.interrupted()){
                return null;
            }

            List<Server> upList = lb.getReachableServers();
            List<Server> allList = lb.getAllServers();

            int serverCount = allList.size();
            if(serverCount == 0){
                return null;
            }
            //随机访问
//            int index = random.nextInt(serverCount);
//            server = upList.get(index);


            //每个五次轮询
            if(total < 5){
                server = upList.get(currentIndex);
                total++;
            }else{
                total=0;
                currentIndex++;
                if(currentIndex >=upList.size()){
                    currentIndex = 0;
                }
            }
            if(server==null){
                Thread.yield();
                continue;
            }
        }
        return server;
    }

    @Override
    public Server choose(Object o) {
        return null;
    }
}
